import {Component, Input, OnInit} from '@angular/core';
import Map from 'ol/Map';
import View from 'ol/View';
import {Image as ImageLayer, Tile as TileLayer} from 'ol/layer';
import RasterSource from 'ol/source/Raster';
import XYZ from 'ol/source/XYZ';
import {UtilComponent} from '../../interface/util-component.interface';
import {fromLonLat} from 'ol/proj.js';
@Component({
    selector: 'kylin-sea-level',
    templateUrl: './sea-level.component.html',
    styleUrls: ['./sea-level.component.less']
})
export class SeaLevelComponent implements OnInit, UtilComponent {
// ---------- 接口实现 begin -------------- //
    hasContent = true;
    map: Map;
    view: View;
    @Input() set data(val) {
        Object.assign(this, val);
    };
    // ---------- 接口实现 end ---------------- //
    tilelayer;
    imglayer;
    raster: RasterSource;
    level = 1;
    constructor() {
    }

    ngOnInit() {
        this.turnOn();
    }

    levelChange(e) {
        this.level = e;
        this.raster.changed();
    }

    flood = (pixels, data) => {
        const pixel = pixels[0];
        if (pixel[3]) {
            const height = -10000 + ((pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1);
            if (height <= data.level) {
                pixel[0] = 145;
                pixel[1] = 175;
                pixel[2] = 186;
                pixel[3] = 255;
            } else {
                pixel[3] = 0;
            }
        }
        return pixel;
    }

    turnOn() {
        const key = 'pk.eyJ1IjoidHNjaGF1YiIsImEiOiJjaW5zYW5lNHkxMTNmdWttM3JyOHZtMmNtIn0.CDIBD8H-G2Gf-cPkIuWtRg';
        const elevation = new XYZ({
            url: 'https://api.mapbox.com/v4/mapbox.terrain-rgb/11/328/791@2x.pngraw?access_token=' + key,
            crossOrigin: 'anonymous',
            transition: 0
        });
        this.raster = new RasterSource({
            sources: [elevation],
            operation: this.flood
        });

        this.tilelayer = new TileLayer({
            source: new XYZ({
                url: 'https://api.mapbox.com/styles/v1/tschaub/ciutc102t00c62js5fqd47kqw/tiles/256/11/328/791?access_token=' + key,
            })
        });

        this.imglayer = new ImageLayer({
            opacity: 0.6,
            source: this.raster
        });

        this.map.addLayer(this.imglayer);
        this.map.addLayer(this.tilelayer);
        this.raster.on('beforeoperations', (event) => {
            event.data.level = this.level;
        });
    }

    cancel(options?: any): any {
        this.map.removeLayer(this.tilelayer);
        this.map.removeLayer(this.imglayer)
    }


}
